/*
** Copyright (C) 2011 Viens Yann
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <fstream>
#include <iostream>
#include "Variables.hpp"
#include "BreakOutLevelLoader.hpp"

BreakOutLevelLoader::BreakOutLevelLoader()
{
}

BreakOutLevelLoader::~BreakOutLevelLoader()
{
  if (_reader)
    _reader.close();
}

void	BreakOutLevelLoader::getInfos(const int nbLines, memberPointer member)
{
  int	currentNbLines = 0;
  char	buffer[BUFFSIZE + 1];

  while (!_reader.eof() && currentNbLines < nbLines)
    {
      memset(buffer, 0, BUFFSIZE + 1);
      _reader.getline(buffer, BUFFSIZE);
      if (buffer[0] != 0)
	(this->*member)(buffer);
      currentNbLines++;
    }
}

void	BreakOutLevelLoader::getDimensions(std::string const& line)
{
  std::string	divWidth = line.substr(0, line.find_first_not_of("0123456789"));
  std::string	divHeight = line.substr(line.find_first_not_of("0123456789") + 1);

  _divWidth = atoi(divWidth.data());
  _divHeight = atoi(divHeight.data());
}

void	BreakOutLevelLoader::getBrick(std::string const& line)
{
  std::string	posX = line.substr(0, line.find_first_not_of("0123456789"));
  std::string	intermediate = line.substr(line.find_first_not_of("0123456789") + 1);
  std::string	posY = intermediate.substr(0, intermediate.find_first_not_of("0123456789"));
  std::string	color = intermediate.substr(intermediate.find("0x") + 2);

  int		posXi = atoi(posX.data()) * _winWidth / _divWidth + BORDERSIZE - ((_winWidth / _divWidth) / 2);
  int		posYi = atoi(posY.data()) * _winHeight / _divHeight - ((_winHeight / _divHeight) / 2);
  int		colori = (int)strtol(color.data(), (char **)NULL, 16);
  Brick*	newBrick = new Brick(posXi, posYi, _winWidth / _divWidth, _winHeight / _divHeight, colori);

  _brickList->push_back(newBrick);
}


std::list<Brick*>*	BreakOutLevelLoader::loadLevel(std::string const& fileName, const int winWidth, const int winHeight)
{
  _reader.open(fileName.data());
  if (_reader)
    {
      _brickList = new std::list<Brick*>();
      _winWidth = winWidth - (BORDERSIZE * 2);
      _winHeight = winHeight;
      getInfos(1, &BreakOutLevelLoader::getDimensions);
      getInfos(DUMMY, &BreakOutLevelLoader::getBrick);
      _reader.close();
      return _brickList;
    }
  return NULL;
}
